import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ahj_app/base/basewidget/HttpUtils/HttpBaseConst.dart';
import 'package:flutter_ahj_app/base/cunchu/UserInfoUtils.dart';
import 'package:flutter_ahj_app/base/pluglin/wxplulin/WxJumpUtils.dart';
import 'package:flutter_ahj_app/base/utils/downloadfile/CommonUtils.dart';
import 'package:flutter_ahj_app/base/utils/permission/PerUtils.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter_ahj_app/base/values/SQColor.dart';
import 'package:flutter_ahj_app/base/values/dimens.dart';
import 'package:flutter_ahj_app/base/utils/HttpNoTokenUtils.dart';
import 'package:flutter_ahj_app/base/bean/show_files_bean.dart';
import 'package:flutter_ahj_app/base/utils/ToastUtils.dart';
import '../mTopBar.dart';
import 'OpenFileUtils.dart';

class DownFilePage extends StatefulWidget {
  String downUrl, filePath, fileName;

  DownFilePage(this.downUrl, this.filePath, this.fileName);

  @override
  State<StatefulWidget> createState() => DownFilePageState();
}

class DownFilePageState extends State<DownFilePage> {
  String _btnText = "开始下载";
  bool _isDownLoading = false; // 是否正在下载
  int _progress = 0, _count = 0, _total = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    getDataFile("0");
  }

  var filelocalPath;
  getDataFile(String type) async {
    var directory;
    if (Platform.isIOS) {
      final dir = await getApplicationDocumentsDirectory();
      // 创建文件夹
      directory = new Directory(
          "${dir.path + Platform.pathSeparator}aqzjzx${Platform.pathSeparator}files");
      filelocalPath = directory.path + Platform.pathSeparator + widget.fileName;
    } else {
      final dir = await getExternalStorageDirectory();
      // 创建文件夹
      directory = new Directory(
          "${dir.path + Platform.pathSeparator}aqzjzx${Platform.pathSeparator}files");
      filelocalPath = directory.path + Platform.pathSeparator + widget.fileName;
    }

    File file = File(filelocalPath);

    bool hasDirectory = await directory.exists();
    bool hasFile = await file.exists();
    if (hasDirectory && hasFile) {
      if (type == "0") {
        file.delete();
      }

      if (type == "1") {
        // 附件已经存在，直接打开
        _btnText = "打开文件";
        WxJumpUtils.wxShareFile({
          "url": filelocalPath,
          "goodsName": widget.fileName,
          "description": "",
        });
        setState(() {});
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        appBar: MTopBar(
                title: "文件下载",
                rightButtonText: "转发",
                onRightButtonClick: CommonUtils.debounce(() {
                  if (_isDownLoading) {
                    return;
                  }

                  if (_btnText == "打开文件") {
                    WxJumpUtils.wxShareFile({
                      "url": filelocalPath,
                      // "url":"www.baidu.com",
                      "goodsName": widget.fileName,
                      "description": "",
                    });
                  } else {
                    widget.downUrl.startsWith("http")
                        ? _down("1")
                        : _getImagePath("3");
                  }
                }, 500))
            .create(),
        body: _body(),
      ),
      onWillPop: () => _back(),
    );
  }

  _back() {
    if (_isDownLoading) {
      //正在下载
      _showDialog(context);
    } else {
      Navigator.pop(context);
    }
  }

  ///获得图片路径
  _getImagePath(type) async {
    var params = {"a": "a"};

    ///fileName  文件名
    /// type  是否是视频1:是 0:不是
    String url = HttpBaseConst.serverUrl +
        HttpBaseConst.downloadPath +
        "?" +
        "fileName=" +
        widget.downUrl +
        "&type=0";
    HttpNoTokenUtils.httpGet(url, params, (result) {
      print(result);

      ShowFilesBean showFilesBean = ShowFilesBean.fromJson(json.decode(result));

      print("我是fileUrl" + showFilesBean.data.fileUrl);
      widget.downUrl = showFilesBean.data.fileUrl;
      if (type == "2") {
        yulan();
      } else if (type == "3") {
        _down("1");
      } else {
        _down("0");
      }
    }, context: context);
  }

  // 提示框
  _showDialog(BuildContext context) {
    StatefulBuilder sb = StatefulBuilder(
      builder: (context, mSetState) {
        return new AlertDialog(
          title: new Text("温馨提示"),
          content: new Text("有文件正在下载，是否中断下载？"),
          actions: <Widget>[
            FlatButton(
                child: Text("是"),
                onPressed: () {
                  Navigator.of(context).pop();
                  _cancleDown();
                }),
            FlatButton(
                child: new Text("否"),
                onPressed: () {
                  Navigator.of(context).pop();
                })
          ],
        );
      },
    );

    showDialog(
        context: context, barrierDismissible: false, builder: (context) => sb);
  }

  _body() {
    Widget body = Padding(
      padding: EdgeInsets.only(
          top: Dimens.dimens96, left: Dimens.dimens48, right: Dimens.dimens48),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Image.asset(
            "img/icon_file.png",
            width: Dimens.dimens80,
            height: Dimens.dimens80,
          ),
          Container(height: Dimens.dimens16),

          Text(
            widget.fileName,
            style: TextStyle(
                color: SQColor.per87Black, fontSize: Dimens.textSize44),
          ),

          Expanded(flex: 1, child: Text("")),

//          new Container(
//            child: new Row(
//              children: [
//                MaterialButton(
//                  shape: RoundedRectangleBorder(
//                      borderRadius:
//                      BorderRadius.all(Radius.circular(Dimens.dimens8))),
//                  color: SQColor.theme_color,
//                  textColor: SQColor.white,
//                  minWidth: double.infinity,
//                  height: Dimens.dimens48,
//                  onPressed: () => widget.downUrl.startsWith("http")?yulan():  _getImagePath("1"),
//                  child: Text(
//                    "查看",
//                    style: TextStyle(fontSize: Dimens.textSize28),
//                  ),
//                ),
//               new Container(
//                 child: new    Offstage(
//                   offstage: _isDownLoading,
//                   child: MaterialButton(
//                     shape: RoundedRectangleBorder(
//                         borderRadius:
//                         BorderRadius.all(Radius.circular(Dimens.dimens8))),
//                     color: SQColor.theme_color,
//                     textColor: SQColor.white,
//                     minWidth: double.infinity,
//                     height: Dimens.dimens48,
//                     onPressed: () => _btnText == "开始下载" ?  widget.downUrl.startsWith("http")?   _down():  _getImagePath("1") : _open(),
//                     child: Text(
//                       _btnText,
//                       style: TextStyle(fontSize: Dimens.textSize28),
//                     ),
//                   ),
//                 ),
//               ) ,
//              ],
//            ),
//          ),
          Offstage(
            offstage: _isDownLoading,
            child: MaterialButton(
              shape: RoundedRectangleBorder(
                  borderRadius:
                      BorderRadius.all(Radius.circular(Dimens.dimens8))),
              color: SQColor.theme_color,
              textColor: SQColor.white,
              minWidth: double.infinity,
              height: Dimens.dimens48,
              onPressed: () => widget.downUrl.startsWith("http")
                  ? yulan()
                  : _getImagePath("2"),
              child: Text(
                "预览",
                style: TextStyle(fontSize: Dimens.textSize28),
              ),
            ),
          ),
          new Container(
            height: 12,
          ),
          Offstage(
            offstage: _isDownLoading,
            child: MaterialButton(
              shape: RoundedRectangleBorder(
                  borderRadius:
                      BorderRadius.all(Radius.circular(Dimens.dimens8))),
              color: SQColor.theme_color,
              textColor: SQColor.white,
              minWidth: double.infinity,
              height: Dimens.dimens48,
              onPressed: () => _btnText == "开始下载"
                  ? widget.downUrl.startsWith("http")
                      ? _down("0")
                      : _getImagePath("1")
                  : _open(),
              child: Text(
                _btnText,
                style: TextStyle(fontSize: Dimens.textSize28),
              ),
            ),
          ),
          Offstage(
            offstage: !_isDownLoading,
            child: Text(
              "下载进度：$_progress%",
              style: TextStyle(
                  color: SQColor.per60Black, fontSize: Dimens.textSize28),
            ),
          ),
          Container(height: Dimens.dimens96)
        ],
      ),
    );
    return body;
  }

  yulan() {
    if (widget.downUrl.contains(".png") ||
        widget.downUrl.contains(".jpg") ||
        widget.downUrl.contains(".JPG") ||
        widget.downUrl.contains(".PNG")) {
      List<String> filePath = [];
      int position = 0;
      filePath.add(widget.downUrl);

      Navigator.pushNamed(context, "/ShowImage",
          arguments: {'position': position, 'filePath': filePath});
    } else if (widget.downUrl.contains(".doc") ||
        widget.downUrl.contains(".docx") ||
        widget.downUrl.contains(".xls") ||
        widget.downUrl.contains(".xlsx") ||
        widget.downUrl.contains(".XLS") ||
        widget.downUrl.contains(".XLSX") ||
        widget.downUrl.contains(".ppt") ||
        widget.downUrl.contains(".pdf") ||
        widget.downUrl.contains(".pptx")) {
      if (Platform.isIOS) {
        String encodeUrl =
            Uri.encodeComponent(base64Encode(utf8.encode(widget.downUrl)));

        String webUrl =
            "https:\u002f\u002ffilesvc.anhuanjia.com\u002fonlinePreview?url=$encodeUrl";

        Navigator.pushNamed(context, "/WebViewUntil",
            arguments: {"title": "预览", "url": webUrl});
      } else {
        // String encodeUrl = Uri.encodeComponent(
        //
        //     widget.downUrl);
        // String webUrl =
        //     "http:\u002f\u002fdocs.xinanyun.cn\u002fop\u002fembed.aspx?src=$encodeUrl";
        // var httpurl=  Uri.encodeComponent(widget.downUrl);
        String encodeUrl;

        // widget.downUrl="https://xalvideo.oss-cn-beijing.aliyuncs.com/t1/1620438143699.docx";

        /* try{
          var dataScore= widget.downUrl.split("?");

          String dataurl= Uri.decodeComponent(dataScore[0]);

          if(dataScore.length>1){
            dataurl=dataurl+"?"+dataScore[1]+"&time="+(DateUtil.getNowDateMs().toString());
          }else{
            dataurl=dataurl+"?time="+(DateUtil.getNowDateMs().toString());
          }
          print(dataurl);
           encodeUrl = Uri.encodeComponent(base64Encode(utf8.encode(dataurl)));
        } catch (e) {
          print(e);
          var httpurl=  Uri.encodeComponent(widget.downUrl);
          var dataScore= httpurl.split("?");

          String dataurl= Uri.decodeComponent(dataScore[0]);

          if(dataScore.length>1){
            dataurl=dataurl+"?"+dataScore[1]+"&time="+(DateUtil.getNowDateMs().toString());
          }else{

          }
          print(dataurl);

    }*/
        var dataurl;
        // if(widget.downUrl.contains("?")){
        //   dataurl=widget.downUrl+"&time="+(DateUtil.getNowDateMs().toString());
        // }else{
        //   dataurl=widget.downUrl+"?time="+(DateUtil.getNowDateMs().toString());
        // }
        encodeUrl =
            Uri.encodeComponent(base64Encode(utf8.encode(widget.downUrl)));
        //
        // var dataScore= widget.downUrl.split("?");
        //
        // String dataurl= Uri.decodeComponent(dataScore[0]);
        //
        // if(dataScore.length>1){
        //   dataurl=dataurl+"?"+dataScore[1];
        // }
        // String encodeUrl = Uri.encodeComponent(base64Encode(utf8.encode(dataurl)));

        String webUrl =
            "https:\u002f\u002ffilesvc.anhuanjia.com\u002fonlinePreview?url=$encodeUrl";

        Navigator.pushNamed(context, "/WebViewPDF", arguments: {
          "title": "预览"
              '',
          "url": webUrl,
          "pdf": widget.downUrl.toLowerCase().endsWith(".pdf") ? true : false,
          "withZoom": true,
        });
      }
    } else if (widget.downUrl.contains(".doc") ||
        widget.downUrl.contains(".docx")) {
    } else if (widget.downUrl.contains(".xls")) {
    } else if (widget.downUrl.contains(".ppt")) {
    } else if (widget.downUrl.contains(".pdf")) {
    } else {
      ToastUtils.showToast("该格式暂不支持预览");
    }
  }

  _cancleDown() async {
    // 创建文件夹
//    File file = File(widget.filePath);
//    if (await file.exists()) {
//      // 附件已经存在，删除文件
//      await file.delete();
//    }
    cancelToken.cancel("cancelled");
    Navigator.pop(context); //关闭对话框
  }

  _open() {
    print("openFile ${widget.filePath}");
    if (Platform.isAndroid) {
      OpenFileUtils.open(widget.filePath);
    } else if (Platform.isIOS) {
      OpenFileUtils.open(widget.filePath);
    }
  }

  CancelToken cancelToken = new CancelToken();

  _down(var type) async {
    // if (Platform.isAndroid) {
    setState(() {
      _isDownLoading = true;
    });
    String result =
        await PerUtils.checkPermission(context, [Permission.storage]);
    if (result == "1") {
      print(widget.downUrl);
      print(widget.filePath);
      Dio dio = new Dio();
      Map<String, dynamic> headers = new Map();
      if (HttpBaseConst.sessionId == null) {
        HttpBaseConst.sessionId = '';
      }
      headers['COOKIE'] = "ASP.NET_SessionId=" +
          HttpBaseConst.sessionId +
          "; " +
          "__sid=" +
          UserInfoUtils.getSID() +
          "; _mid=" +
          UserInfoUtils.getMID().toString() +
          "; apptype=1";
      headers['Accept'] =
          "text/html,application/json,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
      headers['Accept-Encoding'] = "gzip, deflate";
      headers['Accept-Language'] = "zh-CN,zh;q=0.8";
      headers['User-Agent'] =
          "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36 Hutool";
      dio.interceptors.add(InterceptorsWrapper(onRequest:
          (RequestOptions options,
              RequestInterceptorHandler requestInterceptorHandler) async {
        options.headers = headers;
        return requestInterceptorHandler.next(options); //continue
      }, onResponse: (Response response, dd) {
        return dd.next(response); // continue
      }, onError: (DioError e, dd) {
        print(e.toString());
        setState(() {
          _count = 0;
          _total = 0;
          _progress = 0;
          _isDownLoading = false;
          _btnText = "开始下载";
        });
        return dd.next(e); //continue
      }));
      try {
        await dio.download(widget.downUrl, widget.filePath,
            cancelToken: cancelToken, onReceiveProgress: (count, total) {
          setState(() {
            _count = count;
            _total = total;
            try {
              _progress = (_count / _total * 100).toInt();
            } catch (e) {
              _progress = 0;
            }
            if (count > 0 && total > 0 && count == total) {
              // 下载完毕
              _count = 0;
              _total = 0;
              _progress = 0;
              _isDownLoading = false;
              _btnText = "打开文件";
            }
          });
          if (type == "1" && _btnText == "打开文件") {
            getDataFile("1");
          }
        });
      } on DioError catch (e) {
        print(e.response.data);
      }
    }
    // } else if (Platform.isIOS) {}
  }
}
